import { login, getInfo, logout, getMenuList } from '@/api/login';
import * as auth from '@/utils/auth';
import { asyncRouterMap } from '@/router/routers.js';
// { auth.getToken, auth.setToken, auth.removeToken, auth.setUserID, auth.getUserID, auth.removeUserID }
const state = {
  token: auth.getToken(),
  user: {},
  roles: [],
  // 第一次加载菜单时用到
  loadMenus: false,
  userId: auth.getUserID(),
  menus: {}, // 当前人的所有权限树
  menusMap: {}, // 当前人不同权限下的子节点数据
  menusCode: {},
  codes: {},
  permission: {},
  autoPath: {}, // 路由地址
  asyncRouter: [], // 有权限的路由集合
  permissionType: {}, // 权限类型
  routerMap: {}, // 路由树
  searchInfo: {}
};
const user = {
  state: state,
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER: (state, user) => {
      state.user = user;
    },
    SET_USER_ID: (state, Id) => {
      state.userId = Id;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus;
    },
    SET_ROLES_MENUS: (state, menus) => {
      state.menus = menus;
    },
    SET_SEARCH_INFO: (state, searchInfo) => {
      state.searchInfo = searchInfo;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe;
      return new Promise((resolve, reject) => {
        login({ username: userInfo.username, password: userInfo.password }).then(res => {
          const token = res.data.token;
          const userId = res.data.userId;
          auth.setToken(token, rememberMe);
          auth.setUserID(userId);
          commit('SET_TOKEN', token);
          commit('SET_USER_ID', userId);
          getInfo(userId).then(res => {
            // setUserInfo(res.data, commit);
            auth.setUserName(res.data.username);
            console.warn(res.data.roles);
            const roles = res.data.roles.map(rel => {
              return rel.id;
            });
            auth.setUserRoles(roles.join());
            setUserInfo(res.data, commit, 'SET_USER');
            // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js

            // commit('SET_USER', res.data);
            getMenuList().then(res => {
              resolve(res);
              // TODO 注释掉路由调用方法
              // setRoles(res, commit)
            });
          });
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo(user.state.userId).then(res => {
          setUserInfo(res.data, commit, 'SET_USER');
          getMenuList().then(res => {
            commit('SET_LOAD_MENUS', true);
            resolve(setRoles(res, commit));
          });
          // 'SET_ROLES'
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit);
          resolve();
        }).catch(error => {
          logOut(commit);
          reject(error);
        });
      });
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false);
      });
    },
    ChangeSearch({ commit }, searchInfo, type = true) {
      // searchInfo.newTime = +new Date();
      if (type) {
        commit('SET_SEARCH_INFO', JSON.parse(JSON.stringify(searchInfo)));
      } else {
        commit('SET_SEARCH_INFO', searchInfo);
      }
    }
  }
};
const setRoles = (res, commit) => {
  const treeRoles = {};
  const menusCode = {};
  res.data.sort((a, b) => {
    return a.sort - b.sort;
  });
  res.data.map(item => {
    treeRoles[item.id] = item;
    menusCode[changeCode(item.code)] = item;
  });
  const list = [];
  changeRouterMap(asyncRouterMap);
  const Roles = res.data.map(item => {
    const pidNode = treeRoles[item.pid];
    if (pidNode) {
      if (!pidNode.children) {
        pidNode.children = [];
      }
      pidNode.children.push(item);
    }
    treeRoles[item.id] = item;
    menusCode[changeCode(item.code)] = item;
    if (!item.pid) {
      list.push(item);
    }
    return item.code;
  });
  // console.warn(list);
  state.menusMap = treeRoles;
  state.menusCode = menusCode;
  state.asyncRouter = getMenus(list);
  setUserInfo(list, commit, 'SET_ROLES_MENUS');
  setUserInfo(Roles, commit, 'SET_ROLES');
  // console.warn('USER 对象信息：', state);
  return state.asyncRouter;
};

export const logOut = (commit) => {
  commit('SET_TOKEN', '');
  commit('SET_ROLES', []);
  auth.removeToken();
  auth.removeUserID();
  auth.removeUserName();
  auth.removeUserRoles();
};

export const setUserInfo = (res, commit, type) => {
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  // if (res.roles.length === 0) {
  //   commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT']);
  // } else {
  //   commit(type, res.roles);
  // }
  commit(type, res);
};

const isArray = (arr) => {
  return Object.prototype.toString.call(arr) === '[object Array]';
};
const isRouterPath = (url) => {
  const rg = RegExp(/^\/[a-zA-Z]/);
  return rg.test(url);
};
const reuseRg = /^reuse:+/;
const isReuseCode = (code) => {
  const rg = RegExp(reuseRg);
  return rg.test(code);
};
function getOriginalCode(code) {
  return code.replace(new RegExp(reuseRg, 'gm'), '');
}
const optimizePath = (str) => {
  return str.replace(new RegExp(/[\/]+/, 'gm'), '/');
};
const changeCode = (str) => {
  return str.replace(new RegExp(/[\:]+/, 'gm'), '_');
};
// 路由拼装处理
// eslint-disable-next-line no-unused-vars
function getMenus(data) {
  const routerTree = {};
  const _router = [];
  // const resType = {
  //   menu: 'MENU',
  //   element: 'ELEMENT'
  // };
  function forTree(tree, path, baseItem) {
    const code = isReuseCode(tree.code) ? getOriginalCode(tree.code) : tree.code;
    const treeCode = changeCode(code);
    const upperCode = treeCode.toUpperCase();
    const subRouter = state.routerMap[treeCode];
    state.permission[changeCode(tree.code)] = tree;
    // 生成权限常量
    state.permissionType[upperCode] = true;
    state.codes[upperCode] = treeCode;
    // // TODO  此处需要等页面修改为引用方式非路由方式加载页面后方可放开此循环调用
    // // if (tree.type === resType.element) {
    // state.permissionElement.push(code);
    // // } else {
    // state.permissionMenus.push(code);
    // }
    if (subRouter) {
      const activeMenu = state.routerMap[changeCode(baseItem.code)] && state.routerMap[changeCode(baseItem.code)].path;
      subRouter.meta.activeMenu = activeMenu;
      subRouter.meta.baseCode = baseItem.code;
      subRouter.meta.baseKey = changeCode(baseItem.code);
      subRouter.meta.base = baseItem;
      subRouter.meta.menus = tree;
      const children = tree.children;
      const routerPath = optimizePath((path || '') + (isRouterPath(subRouter.path) ? '' : '/') + subRouter.path);
      subRouter.path = routerPath;
      if (!(isReuseCode(tree.code) && !!state.autoPath[upperCode])) {
        state.autoPath[upperCode] = routerPath;
      }

      if (children && children.length > 0) {
        children.map((item) => {
          const itemCode = isReuseCode(item.code) ? getOriginalCode(item.code) : item.code;
          const router = state.routerMap[changeCode(itemCode)];
          if (router) {
            if (!subRouter.children) {
              subRouter.children = [];
            }
            subRouter.children.push(router);
          }
          forTree(item, routerPath, baseItem);
        });
        // 如果子项中有子路由跳转，需要增加Route-view 标签，便于子项显示
        if (subRouter.children && subRouter.children.length > 0 && !subRouter.meta.redirect && tree.pageUrl !== 'search') {
          const skip = {
            path: subRouter.path + '/skip',
            component: subRouter.component,
            name: 'skip',
            hidden: true,
            meta: { ...subRouter.meta }
          };
          subRouter.children.unshift(skip);
          subRouter.redirect = optimizePath(subRouter.children[0].path);
          // subRouter.component = (resolve) => require(['@/layout/index'], resolve);
          subRouter.component = (resolve) => require(['@/layout/components/OtherMain'], resolve);
        }
        if (subRouter.meta.redirect) {
          subRouter.redirect = optimizePath(subRouter.children[0].path);
        }
      }
      routerTree[changeCode(tree.code)] = subRouter;
    }
  }
  if (isArray(data)) {
    data.map((item) => {
      forTree(item, null, item);
      const routers = routerTree[changeCode(item.code)];
      if (routers) {
        _router.push(routers);
      }
    });
  } else {
    forTree(data);
  }
  // console.warn('路由数据信息', _router);
  state.routerMap = routerTree;
  return _router;
}
function changeRouterMap(data) {
  if (JSON.stringify(state.routerMap) !== '{}') return;
  const routerMap = {};
  data.map(e => {
    // console.warn(changeCode(e.meta.code));
    routerMap[changeCode(e.meta.code)] = e;
    // if (e.meta.createChildren) {
    //   const { subComponent: component, subPath: path, code, title, hidden = false } = e.meta;
    //   e.children = [{
    //     path,
    //     meta: { code, title },
    //     code,
    //     hidden,
    //     component
    //   }];
    // }
  });
  console.warn(routerMap);
  state.routerMap = { ...routerMap };
}

export default user;
